export interface EnergyData {
  solar: {
    totalGeneration: {
      today: string;
      total: string;
    };
  };
  grid: {
    export: {
      today: string;
      total: string;
    };
    import: {
      today: string;
      total: string;
    };
  };
  battery: {
    export: {
      today: string;
      total: string;
    };
    import: {
      today: string;
      total: string;
    };
  };
  home: {
    totalConsumption: {
      today: string;
      total: string;
    };
  };
}

export interface EnergyFlowData {
  solar: {
    power: number;
  };
  grid: {
    power: number;
  };
  battery: {
    power: number;
  };
  load: {
    power: number;
  };
}

export interface AlertData {
  count: number;
}

export interface SystemStatusData {
  communication: {
    status: string;
  };
  energyPlan: {
    mode: string;
  };
  gridStatus: {
    status: string;
  };
  batterySOC: {
    percentage: number;
  };
}

export interface BasicInfoData {
  batteryCapacity: number;
  stringCapacity: number;
  createDate: string;
  installer: string;
  clientClassification: string;
  client: string;
  countryRegion: string;
  address: string;
  checkModel: number;        // 用电计划模式: 0-autoModel, 12-zenKi_Mode
  socLevel: number;          // 电池SOC百分比
  state: number;             // 通信状态: 1正常 2离线
}

// 模拟数据函数 - 已注释，准备替换为真实API调用
// export const getMockEnergyData = (): EnergyData => {
//   return {
//     solar: {
//       totalGeneration: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       }
//     },
//     grid: {
//       export: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       },
//       import: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       }
//     },
//     battery: {
//       export: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       },
//       import: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       }
//     },
//     home: {
//       totalConsumption: {
//         today: "2,331.99 kWh",
//         total: "2,331.99 kWh"
//       }
//     }
//   };
// };

// export const getMockEnergyFlowData = (): EnergyFlowData => {
//   return {
//     solar: {
//       power: 21.99
//     },
//     grid: {
//       power: 0.99
//     },
//     battery: {
//       power: 2.12
//     },
//     load: {
//       power: 0.99
//     }
//   };
// };

// export const getMockAlertData = (): AlertData => {
//   return {
//     count: 8
//   };
// };

// export const getMockSystemStatusData = (): SystemStatusData => {
//   return {
//     communication: {
//       status: "Normal"
//     },
//     energyPlan: {
//       mode: "Auto Mode"
//     },
//     gridStatus: {
//       status: "On gird"
//     },
//     batterySOC: {
//       percentage: 2
//     }
//   };
// };

// export const getMockBasicInfoData = (): BasicInfoData => {
//   return {
//     batteryCapacity: 12400,
//     stringCapacity: 800,
//     createDate: "2025-02-12",
//     installer: "Karl Max",
//     clientClassification: "Organization",
//     client: "Samm ywc",
//     countryRegion: "Sweden",
//     address: "Apt. 268Crooks Village, New Gillianhaven"
//   };
// };

// 新增：App端API调用函数
import { systemAppApi } from "@/api/business";

/**
 * 获取系统详情数据
 */
export async function getSystemDetail(systemId: string) {
  try {
    // 按文档：POST JSON，字段名为驼峰。优先 hemsId；若非纯数字，则走 deviceKey
    const isNumeric = /^\d+$/.test(String(systemId));
    const payload: any = isNumeric
      ? { hemsId: Number(systemId) }
      : { deviceKey: String(systemId) };
    const response = await systemAppApi.getDetail(payload);
    
    if ((response.code === 0 || response.code === 200) && response.data) {
      const data = response.data;
      
      // 解析地址信息（如果是JSON字符串）
      let addressInfo = '';
      try {
        if (typeof data.address === 'string' && data.address.startsWith('{')) {
          const addressObj = JSON.parse(data.address);
          addressInfo = addressObj.local || addressObj.address || data.address;
        } else {
          addressInfo = data.address || '';
        }
      } catch {
        addressInfo = data.address || '';
      }
      
      const mappedData = {
        batteryCapacity: data.batteryCapacity || 0,
        stringCapacity: data.solar || data.stringCapacity || 0,
        createDate: data.createTime || data.crateDate || '',
        installer: data.installer || '',
        clientClassification: data.company || '',
        client: data.consumer || data.client || '',
        countryRegion: data.country || data.region || '',
        address: addressInfo,
        checkModel: data.checkModel || 0,
        socLevel: data.socLevel || 0,
        state: data.state || 0
      };
      
      return mappedData;
    }
    return null;
  } catch (error) {
    console.error('获取系统详情失败:', error);
    return null;
  }
}

/**
 * 能源统计数据接口，用于映射 /installer/web/energy 接口的响应
 */
// export interface EnergySummaryData {
//   solarGeneration: number; // 对应 Total Solar Generation
//   homeConsumption: number; // 对应 Total Consumption
//   gridExport: number;      // 对应 Export to grid
//   gridImport: number;      // 对应 Import from grid
//   batteryCharge: number;   // 对应 Charge to battery
//   batteryDischarge: number; // 对应 Discharge from battery
// }

/**
 * 获取能源统计数据
 */
// export async function getEnergyStats(systemId: string): Promise<EnergySummaryData | null> {
//   try {
//     console.log('调用 getEnergyStats，systemId:', systemId);

//     // 根据接口文档，/installer/web/energy 接口可能需要 systemId 作为查询参数
//     const response = await systemAppApi.getEnergyStats({
//       hemsId: systemId,
//       // 根据实际接口文档添加其他必要的参数，例如时间范围等
//       // current: 1,
//       // size: 1
//     });

//     console.log('getEnergyStats API 响应:', response);

//     // 根据实际 API 响应的成功条件进行判断 (code === 0 或 code === 200)
//     if (response.code === 0 && response.data) {
//       const data = response.data;
//       console.log('getEnergyStats 原始数据:', data);

//       const mappedData: EnergySummaryData = {
//         solarGeneration: data.solar || 0, // 假设接口返回字段为 solar
//         homeConsumption: data.outputToHome || 0, // 假设接口返回字段为 outputToHome
//         gridExport: data.outputToGrid || 0, // 假设接口返回字段为 outputToGrid
//         gridImport: data.gridInput || 0, // 假设接口返回字段为 gridInput
//         batteryCharge: data.batteryInput || 0, // 假设接口返回字段为 batteryInput
//         batteryDischarge: data.batteryOutput || 0 // 假设接口返回字段为 batteryOutput
//       };

//       console.log('getEnergyStats 映射后数据:', mappedData);
//       return mappedData;
//     }
//     return null;
//   } catch (error) {
//     console.error('获取能源统计数据失败:', error);
//     return null;
//   }
// }